<template>
  <div>
    <el-form>
      <div class="params head-form">
        <el-form-item label="核销状态">
          <el-select placeholder="请选择" v-model="params.cancelState" style="flex: 1" @change="init">
            <el-option v-for="(item, index) in verificationType" :value="index" :label="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="params-select">
            <el-select v-model="params.type" placeholder="请选择" style="width: 135px" @change="init">
              <el-option v-for="(item, index) in type" :label="item" :value="Number(index)" />
            </el-select>
            <collaborators-query v-model:model-value="params.partnerId" :type="params.type" @flushed="init" />
          </div>
        </el-form-item>
        <el-form-item label="编号">
          <el-input v-model="params.slipCode" placeholder="请输入编号" style="flex: 1" @keyup.enter="init" @blur="init" />
        </el-form-item>
        <el-form-item>
          <div class="params-select">
            <el-select v-model="params.moneyType" placeholder="请选择" style="width: 135px" @change="init">
              <el-option label="应付金额" :value="1" />
              <el-option label="已付金额" :value="1" />
              <el-option label="未付金额" :value="1" />
            </el-select>
            <input-range v-model="params.amount" @change="init" />
          </div>
        </el-form-item>
        <el-form-item label="收款账户">
          <el-input placeholder="请输入" v-model="params.account" @keyup.enter="init" @blur="init" />
        </el-form-item>
        <el-form-item label="创建人">
          <created-by v-model="params.createId" @change="init" />
        </el-form-item>
        <el-form-item label="添加时间">
          <el-date-picker
            v-model="params.date"
            :teleported="false"
            style="flex: 1"
            type="daterange"
            range-separator="—"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="init"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button :icon="RefreshRight" plain type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="table-operate">
      <el-button type="primary" :disabled="!checkedList.length" @click="openBatchPay">批量支付</el-button>
    </div>
    <div class="table">
      <el-table :data="data" max-height="calc(100vh - 480px)">
        <el-table-column prop="slipCode" label="编号" width="160" />
        <el-table-column prop="businessType" label="业务类型" />
        <el-table-column prop="partner" label="合作方" min-width="150" />
        <el-table-column prop="city" label="核销状态" width="90">
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.cancelState == 1">待核销</el-tag>
            <el-tag type="primary" v-else-if="scope.row.cancelState == 2">部分核销</el-tag>
            <el-tag type="success" v-else>已核销</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="收款人" width="260">
          <template #default="scope">
            {{ splicing(cleanArray([scope.row.payName, scope.row.account, scope.row.accountName, scope.row.bankName]), "-") }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="应付金额" width="120">
          <template #default="scope"> ￥{{ scope.row.plainMoney }} </template>
        </el-table-column>
        <el-table-column prop="address" label="已付金额" width="120">
          <template #default="scope"> ￥{{ scope.row.inMoney }} </template>
        </el-table-column>
        <el-table-column prop="zip" label="未付金额" width="120">
          <template #default="scope"> ￥{{ scope.row.outMoney }} </template>
        </el-table-column>
        <el-table-column prop="addDate" label="添加时间" width="180" />
        <el-table-column prop="orderCode" label="关联单据" width="180">
          <template #default="scope">
            <div class="link" @click="toPath('/finance/reimbursed-manage', { billNoteId: scope.row.orderCode })">
              {{ scope.row.orderCode }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="230">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="openDetail(scope.row)">详情</el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="
                toPath('/finance/payments', {
                  slipCode: scope.row.slipCode,
                  slipType: 5
                })
              "
            >
              支付流水
            </el-button>
            <el-button type="primary" link size="small" v-if="scope.row.outMoney > 0" @click="openPay(scope.row)"
              >去支付</el-button
            >
          </template>
        </el-table-column>
        <template #empty>
          <el-empty />
        </template>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:current-page="query.current"
        v-model:page-size="query.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="init"
        @current-change="init"
      />
    </div>
    <el-dialog v-model="detailVisible" width="500" center align-center :show-close="false">
      <template #title>
        <div class="modal-title">
          <custom-title title="报销付款单详情" /><el-icon @click="detailVisible = false">
            <Close />
          </el-icon>
        </div>
      </template>
      <div class="detail">
        <div>
          <div>
            报销付款单编码：<span class="black">{{ detail.slipCode }}</span>
          </div>
          <el-tag type="warning" v-if="detail.cancelState == 1">待核销</el-tag>
          <el-tag type="primary" v-else-if="detail.cancelState == 2">部分核销</el-tag>
          <el-tag type="success" v-else>已核销</el-tag>
        </div>
        <div>
          关联合作方<span class="black">{{ detail.partner }}</span>
        </div>
        <div>
          关联报销单<span class="black">{{ detail.orderCode }}</span>
        </div>
        <div>
          应付金额<span class="black">￥{{ detail.plainMoney }}</span>
        </div>
        <div>
          已付金额<span class="black">￥{{ detail.inMoney }}</span>
        </div>
        <div>
          未付金额<span class="black">￥{{ detail.outMoney }}</span>
        </div>
        <div>
          备注<span class="black">{{ detail.remark }}</span>
        </div>
      </div>
    </el-dialog>
    <el-dialog v-model="payVisible" width="600" center align-center :show-close="false" @close="resetPay">
      <template #title>
        <custom-title :title="`报销付款单${isBatch ? '批量支付' : '支付'}`" />
      </template>
      <div class="info">
        报销付款单编号：<span>{{ detail.slipCode }}</span>
        <div class="card">
          <div>
            <div>
              <div>关联合作方</div>
              <div>{{ detail.partner }}</div>
            </div>
            <div>
              <div>应付金额</div>
              <div>￥{{ detail.plainMoney }}</div>
            </div>
            <div>
              <div>已付金额</div>
              <div>￥{{ detail.inMoney }}</div>
            </div>
            <div>
              <div>未付金额</div>
              <div>￥{{ detail.outMoney }}</div>
            </div>
          </div>
        </div>
      </div>
      <el-form :model="payForm" label-position="top" ref="payFormRef" :rules="payRules">
        <el-form-item label="本次付款金额" prop="money">
          <el-input v-model="payForm.money" @blur="setMoney" @keyup.enter="setMoney" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="付款日期" prop="receiptDate">
          <el-date-picker
            style="flex: 1"
            v-model="payForm.receiptDate"
            type="date"
            placeholder="请选择"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="支付方式" prop="payType">
          <el-radio-group v-model="payForm.payType" @change="payFormRef.clearValidate()">
            <el-radio :value="1" label="账户支付" />
            <el-radio :value="4" label="抵扣借款单" v-if="!isBatch" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="付款账户" prop="payAccountId" v-if="payForm.payType != 4">
          <el-select v-model="payForm.payAccountId">
            <el-option
              v-for="item in account"
              :key="item.accountId"
              :value="item.accountId"
              :label="splicing(cleanArray([item.dictName, item.account, item.accountName]), '-')"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款账户" v-if="payForm.payType != 4">
          <div class="preview">
            {{ splicing([detail.payType, detail.partnerAccountName, detail.accountName]) }}
          </div>
        </el-form-item>

        <el-form-item label="支付凭证" prop="fileVos" v-if="payForm.payType != 4">
          <div>
            <el-upload class="avatar-uploader" multiple :show-file-list="false" :http-request="customRequest">
              <div class="list">
                <div class="code" v-for="item in payForm.fileVos" :key="item">
                  <img :src="item.fileUrl" />
                  <div class="del">
                    <el-icon @click.stop="delImg(item)">
                      <DeleteFilled />
                    </el-icon>
                  </div>
                </div>
                <el-icon class="upload" v-if="payForm.fileVos.length < 6">
                  <Plus />
                  <span>点击上传</span>
                </el-icon>
              </div>
            </el-upload>
            <div class="tip">注：支持{{ fileType }}格式，单张大小不超过{{ maxSize }}MB，只支持{{ maxCount }}张</div>
          </div>
        </el-form-item>
        <el-form-item v-if="payForm.payType == 4">
          <div style="flex: 1">
            <div class="pay-table">
              <div>
                <div>借款还款单号</div>
                <div>应还金额金额</div>
                <div>本单还款</div>
              </div>
              <el-empty v-if="!payForm.advancesReceivedList.length" :image-size="80" />
              <el-scrollbar max-height="150px">
                <div class="table-row" v-for="item in payForm.advancesReceivedList" :key="item.slipId">
                  <div>{{ item.slipCode }}</div>
                  <div>￥{{ item.money }}</div>
                  <div>
                    <el-form-item :prop="item.slipId">
                      {{ item.useMoney || 0 }}
                    </el-form-item>
                  </div>
                </div>
              </el-scrollbar>
            </div>
            <div class="tip">提示：多条借款单系统会优先抵扣借款还款单生成时间更近的</div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="payVisible = false">取消</el-button>
          <el-button type="primary" @click="payComfirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { RefreshRight, Plus } from "@element-plus/icons-vue";
import { getList, pay, getCount } from "@/apis/invoices";
import { ElMessage } from "element-plus";
import { getLoanList, getDetail } from "@/apis/reimbursedPay";
import { getList as getMyAccountList } from "@/apis/myAccount";
import { type, verificationType } from "@/utils/config";
import { splicing, cleanArray } from "@/utils";
import { useRoute } from "vue-router";
import uploadFile from "@/utils/uploadFile";

const route = useRoute();
const emit = defineEmits(["to"]);
const toPath = (path, query) => {
  emit("to", path, query);
};
const payFormRef = ref(null);
const query = ref({
  current: 1,
  size: 10
});
const account = ref([]);
const params = ref({
  serviceType: 5,
  slipCode: route.query.slipCode
});
const reset = () => {
  params.value = {
    serviceType: 5
  };
  init();
};
const resetPay = () => {
  payFormRef.value.resetFields();
  payForm.value = {
    payType: 1,
    fileVos: [],
    advancesReceivedList: {}
  };
};
const setMoney = () => {
  let money = payForm.value.money;
  payForm.value.advancesReceivedList.forEach(item => {
    if (money) {
      item.useMoney = (Number(item.money) < Number(money) ? Number(item.money) : Number(money)).toFixed(2);
      money -= item.useMoney;
    } else {
      item.useMoney = 0;
    }
  });
};
const detailVisible = ref(false);
const payVisible = ref(false);

const payForm = ref({
  payType: 1,
  fileVos: [],
  advancesReceivedList: {}
});
const detail = ref({});
const total = ref(0);
const data = ref([]);
const count = ref({
  outMoney: 0,
  inMoney: 0,
  plainMoney: 0
});
const payRules = {
  payType: [{ required: true, message: "请选择支付方式", trigger: "blur" }],
  receiptDate: [{ required: true, message: "请选择收款日期", trigger: "blur" }],
  fileVos: [{ required: true, message: "请上传收款凭证", trigger: "blur" }],
  money: [
    { required: true, message: "请输入收款金额", trigger: "blur" },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的金额", trigger: "blur" }
  ],
  accountId: [{ required: true, message: "请选择收款账户", trigger: "blur" }],
  payAccountId: [{ required: true, message: "请选择付款账户", trigger: "blur" }]
};
const delImg = img => {
  payForm.value.fileVos = payForm.value.fileVos.filter(item => item.fileId != img.fileId);
};
const checkedList = ref([]);
/**
 * 选择
 */
const handleSelectionChange = newSelection => {
  checkedList.value = newSelection;
};
/**
 * 打开批量弹窗
 */
const openBatchPay = () => {
  if (!checkedList.value.every(v => v.partnerId == checkedList.value[0].partnerId))
    return ElMessage.error("只能相同供应商且相同收款账户可以批量支付，若有特殊需要请单条进行支付！");
  if (!checkedList.value.every(v => v.partnerAccountId == checkedList.value[0].partnerAccountId))
    return ElMessage.error("只能相同供应商且相同收款账户可以批量支付，若有特殊需要请单条进行支付！");
  openPay(
    {
      ...checkedList.value[0],
      slipCode: checkedList.value.map(v => v.slipCode).join(","),
      plainMoney: checkedList.value.reduce((a, b) => a + Number(b.plainMoney), 0).toFixed(2),
      inMoney: checkedList.value.reduce((a, b) => a + Number(b.inMoney), 0).toFixed(2),
      currentPlainMoney: checkedList.value.reduce((a, b) => a + Number(b.currentPlainMoney), 0).toFixed(2),
      slipId: checkedList.value.map(v => v.slipId)
    },
    true
  );
};
const openDetail = item => {
  detailVisible.value = true;
  detail.value = { ...item };
};
const isBatch = ref(false);
const openPay = async (item, batch) => {
  isImgMax.value = false;
  isBatch.value = batch;
  if (!batch) {
    const res = await getDetail(item.slipId);
    detail.value = res.data;
  } else {
    detail.value = { ...item };
  }
  const loanRes = await getLoanList(item.partnerId);
  payForm.value.advancesReceivedList = loanRes.data;
  payVisible.value = true;
};
const isImgMax = ref(false);
const maxSize = ref(20);
const maxCount = ref(6);
const fileType = ref("JPG/JPEG/PNG");
const customRequest = async options => {
  const type = ["image/jpg", "image/jpeg", "image/png"];
  const { file } = options;
  if (!type.includes(file.type)) {
    ElMessage.error("图片格式错误");
    return false;
  } else if (file.size / 1024 / 1024 > maxSize.value) {
    ElMessage.error(`图片大小不能超过${maxSize.value}MB!`);
    return false;
  }
  const fileInfo = await uploadFile(options);
  if (payForm.value.fileVos.length < maxCount.value) {
    payForm.value.fileVos.push({ fileUrl: fileInfo.url, fileName: fileInfo.name, fileId: fileInfo.uid });
  } else {
    if (!isImgMax.value) ElMessage.error(`最多上传${maxCount.value}张图片`);
    isImgMax.value = true;
  }
};
const payComfirm = () => {
  const next = async () => {
    if (isBatch.value) {
      try {
        const res = await batchPay({
          ...payForm.value,
          type: undefined,
          slipIds: detail.value.slipId,
          money: Number(payForm.value.money)
        });
        closeCallback(res);
        payVisible.value = false;
        init();
        ElMessage.success("操作成功");
      } catch (error) {
        console.log(error);
      }
    } else {
      try {
        await pay({
          ...payForm.value,
          type: undefined,
          slipId: detail.value.slipId,
          money: Number(payForm.value.money),
          loanBillList: payForm.value.advancesReceivedList
            .map(item => ({ slipId: item.slipId, money: item.useMoney }))
            .filter(v => Number(v.money))
        });
        payVisible.value = false;
        init();
        ElMessage.success("操作成功");
      } catch (error) {}
    }
  };
  payFormRef.value.validate(async valid => {
    if (!valid) return;
    if (payForm.value.payType == 2) {
      next();
    } else {
      next();
    }
  });
};
const init = async () => {
  const minAmount = params.value.amount ? params.value.amount[0] : undefined;
  const maxAmount = params.value.amount ? params.value.amount[1] : undefined;
  const createdTimeBegin = params.value.date ? params.value.date[0] + " 00:00:00" : undefined;
  const createdTimeEnd = params.value.date ? params.value.date[1] + " 23:59:59" : undefined;
  const paramsData = {
    ...params.value,
    minAmount,
    maxAmount,
    createdTimeBegin,
    createdTimeEnd
  };
  delete paramsData.date;
  delete paramsData.amount;
  const res = await getList(query.value, paramsData);
  data.value = res.data.list;
  total.value = res.data.total;
  const counts = await getCount(paramsData);
  count.value = counts.data ? counts.data : { outMoney: 0, inMoney: 0, plainMoney: 0 };
};
const getAccount = async () => {
  const res = await getMyAccountList({ current: 1, size: 100000 }, { status: 1 });
  account.value = res.data.list;
};
onMounted(() => {
  getAccount();
  init();
});
</script>

<style lang="scss" scoped>
@import "../comon.scss";
</style>
